<?php
/*
 * @Description:设备许可证管理
 * @FilePath: \auxface_certificate\app\certificate\controller\user\v1\MachineRisk.php
 */

declare(strict_types=1);

namespace app\certificate\controller\user\v1;

use DateTime;
use think\facade\Db;
use think\Request;

class MachineRisk
{
    /**
     * @Description: 获取许可证列表
     * @param {Request} $request
     */
    public function getList(Request $request)
    {
        $data        = $request->data;
        $limit       = $data['limit'];
        $page        = $data['page'];
        $searchWhere = [
            ['r.isDelete', '=', '0'],
        ];
        //当前用户待填写的表单
        $getCurrentToSubFormUuids = $this->getCurrentToSubFormUuids($request->uuid) ?: [];
        //状态,待审核-0,审核通过-1，已过期-2,待填写-3
        if (!empty($data['status']) || (isset($data['status']) && $data['status'] == 0)) {
            if ($data['status'] == 2) {
                array_push($searchWhere, ['r.expiredTime', '<', date('Y-m-d H:i:s')]);
            } else if ($data['status'] == 3) {
                array_push($searchWhere, ['r.status', '=', 0]);
                array_push($searchWhere, ['r.expiredTime', '>', date('Y-m-d H:i:s')]);
            } else {
                array_push($searchWhere, ['r.status', '=', $data['status']]);
                array_push($searchWhere, ['r.expiredTime', '>', date('Y-m-d H:i:s')]);
            }
            //数据隔离
            if ($data['status'] == 3) {
                array_push($searchWhere, ['r.uuid', 'IN', $getCurrentToSubFormUuids]);
            } elseif(empty($data['machineUuid'])|| $data['status']!=1){
                //获取当前提交过的许可证
                $riskUuids = DB::table('certificate_machineRiskRecord')->where('wxappUserUuid', $request->uuid)->group('riskUuid')->column('riskUuid') ?? [];
                array_push($searchWhere, ['r.uuid', 'IN', $riskUuids]);
            }
        }
        if (!empty($data['machineUuid'])) array_push($searchWhere, ['r.machineUuid', '=', $data['machineUuid']]);
        if (!empty($data['areaUuid'])) array_push($searchWhere, ['r.areaUuid', '=', $data['areaUuid']]);
        if (!empty($data['typeUuid'])) array_push($searchWhere, ['r.typeUuid', '=', $data['typeUuid']]);
        $list = DB::table('certificate_machineRisk')
            ->alias('r')
            ->leftjoin('certificate_machineRiskType rt', 'r.typeUuid = rt.uuid')
            ->leftjoin('certification_projectWorker w', 'w.wxappUserUuid = r.wxappUserUuid')
            ->leftjoin('certificate_digitalmachine m', 'm.uuid = r.machineUuid')
            ->where($searchWhere)
            ->order(['r.id desc'])
            ->page((int)$page, (int)$limit)
            ->field(['rt.name as typeName', 'w.workerName', 'r.inDate', 'r.status', 'r.uuid', 'r.expiredTime', 'rt.subFormUuids','m.prjMachineCode','m.name as machineName'])
            ->group('r.id')
            ->select()->toArray();
        foreach ($list as &$item) {
            // $typeName = DB::table('certificate_digitalmachinetype')->where("uuid", $item['digitalMacineTypeUuid'])->value('name');
            
            // $item['machineName'] = $typeName.'-'.$item['prjMachineCode'].'號機';

            $item['inDate'] = date('Y-m-d', strtotime($item['inDate']));
            //关联的附表
            $item['subFormUuids'] = DB::table('certificate_machineRiskSubForm')->where('riskUuid', $item['uuid'])->column('subFormUuid') ?: [];
            if ($item['subFormUuids']) {
                $item['subformList'] =  DB::table('certificate_subform')->whereIn('uuid', $item['subFormUuids'])->field('uuid,name')->select();
            } else {
                $item['subformList'] = [];
            }
            //状态,待审核-0,审核通过-1，已过期-2
            if (strtotime($item['expiredTime']) < time()) {
                $item['status'] = '2'; //已过期
            } else if ($data['status'] == 3) {
                $item['status'] = '3'; //待填写
            }
        }
        $result['list'] = $list;
        //待填写数量
        $result['toSubCount'] = $this->getToSubCount($getCurrentToSubFormUuids, $data);
        //是否有新增权限,具有申请表权限+驾驶舱人员
        $result['hasAuth'] =  $this->hasAuth($request, $data);

        return result(SUCCESS, $result, '');
    }

    /**
     * 获取详情
     *
     * @param Request $request
     * @return void
     */
    public function getDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];
        $where = [
            'r.isDelete' => 0,
            'r.uuid' => $uuid
        ];
        //查看有没有提交过的记录
        $riskData = DB::table('certificate_machineRisk')
            ->alias('r')
            ->leftJoin('certificate_machineRiskType rt', 'r.typeUuid = rt.uuid')
            ->leftJoin('certificate_area a', 'a.uuid=r.areaUuid')
            ->where($where)
            ->order('r.id DESC')
            ->field(['r.expiredTime', 'r.status', 'r.uuid', 'r.typeUuid', 'r.areaUuid', 'a.name as areaName', 'rt.name as typeName'])
            ->findOrEmpty();
            dd($riskData);
        if (!$riskData) return result(FAIL, '', '獲取失敗，請返回重試');
       
        $getCurrentToSubFormUuids = [];
        if($riskData['status']!=1) $getCurrentToSubFormUuids = $this->getCurrentToSubFormUuids($request->uuid);
        $getCurrentToSubFormUuids = $this->getCurrentToSubFormUuids($request->uuid);
        if (strtotime($riskData['expiredTime']) < time()) {
            $riskData['status'] = '2'; //已过期
        } else if (in_array($riskData['uuid'], $getCurrentToSubFormUuids)) {
            $riskData['status'] = '3'; //已过期
        }

        $riskRecord = DB::table('certificate_flowForm')
            ->alias('ff')
            ->join('certificate_machineRiskRecord r', 'r.flowFormUuid = ff.uuid')
            ->where('r.riskUuid', $uuid)
            ->order('ff.showOrder asc, ff.flowOrder asc,r.id asc')
            ->field('r.riskUuid,r.uuid,ff.name,ff.subtitle,r.formData')
            ->group('r.uuid')
            ->select()->toArray();
        foreach ($riskRecord as $key => $item) {
            $riskRecord[$key]['formData'] = json_decode(html_entity_decode($item['formData']), true);
        }
        $riskData['riskRecord'] = $riskRecord;

        $canSubFormUUids = $this->canSubForm($riskData['uuid']);
        $riskData['hasNext'] = $riskData['hasAuth'] = 0;
        $riskData['currentData'] = $riskData['nextData'] = [];
        //获取当前用户拥有的表单信息
        $currentFormData = DB::table('certificate_flowForm')
            ->alias('ff')
            ->join('certificate_flowFormWorker fw', 'fw.flowFormUuid = ff.uuid')
            ->where('fw.wxappUserUuid', $request->uuid)
            ->whereIn('ff.uuid', $canSubFormUUids)
            ->where('fw.isDelete', 0)
            ->order('ff.flowOrder asc')
            ->field('ff.uuid as formUuid,ff.name,ff.subtitle,ff.formData,ff.linkForms,ff.type,ff.flowUuid,ff.flowOrder')
            ->find();
        if ($currentFormData) {
            $formData = json_decode(html_entity_decode($currentFormData['formData']), true);
            $currentData['formData']['uuid'] = $currentFormData['formUuid'];
            $currentData['formData']['name'] = $currentFormData['name'];
            $currentData['formData']['subtitle'] = $currentFormData['subtitle'];
            $currentData['formData']['formData'] = $this->formatFormData($riskData['typeUuid'], $formData);
            $linkForms = $currentFormData['linkForms'] ? json_decode($currentFormData['linkForms'], true) : [];
            if ($linkForms) {
                $linkForms = DB::table('certificate_flowForm')
                    ->alias('ff')
                    ->join('certificate_machineRiskRecord r', 'r.flowFormUuid = ff.uuid')
                    ->where(['r.riskUuid'=>$uuid])
                    ->whereIn('ff.uuid', $linkForms)
                    ->order('ff.showOrder asc,ff.flowOrder asc,r.id asc')
                    ->field('ff.uuid,ff.name,r.formData,ff.subtitle')
                    ->group('ff.uuid')
                    ->select()->toArray();
                foreach ($linkForms as $key => $item) {
                    $linkForms[$key]['formData'] = json_decode(html_entity_decode($item['formData']), true);
                }
            }

            //是否有下一次提交
            $canNextSubFormUUids = $this->canSubForm($riskData['uuid'], 0, $currentFormData['flowUuid'], $currentFormData['formUuid'], $currentFormData['flowOrder'], $currentFormData['type']);
            $nextFormData = DB::table('certificate_flowForm')
                ->alias('ff')
                ->join('certificate_flowFormWorker fw', 'fw.flowFormUuid = ff.uuid')
                ->where('fw.wxappUserUuid', $request->uuid)
                ->whereIn('ff.uuid', $canNextSubFormUUids)
                ->where('fw.isDelete', 0)
                ->find();
            if ($nextFormData) {
                $riskData['hasNext'] = 1;
                $riskData['nextData'] = $nextFormData;
            }

            $currentData['linkForms'] = $linkForms;
            $riskData['currentData'] = $currentData;
            $riskData['hasAuth'] = 1;
        }
        return result(SUCCESS, $riskData, '');
    }

    /**
     * @Description: 设备许可证申请
     * @param {Request} $request
     */
    public function apply(Request $request)
    {
        $data  = $request->data;
        $wxappUserUuid = $request->uuid;
        $machineUuid = $data['machineUuid'];
        $machine = DB::table('certificate_digitalMachine')
            ->alias('m')
            ->join('certificate_digitalMachineType t', 't.uuid = m.digitalMacineTypeUuid')
            ->where(['m.isDelete' => 0, 'm.uuid' => $machineUuid])->field('t.machineRiskTypeUuid')
            ->find();
        if (!$machine) return result(FAIL, '', '设备不存在');
        $formData = is_array($data['formData']) ? json_encode($data['formData'], JSON_UNESCAPED_UNICODE) : $data['formData'];
        $formData = html_entity_decode($formData);
        $type = DB::table('certificate_machineRiskType')->where(['isDelete' => 0, 'uuid' => $machine['machineRiskTypeUuid']])->find();
        if (!$type) return result(FAIL, '', '许可证类型已被删除或错误！');

        $flowForm = Db::table('certificate_flowForm')->where('uuid', $data['flowFormUuid'])->find();
        if (!$flowForm) return result(FAIL, '', '流程表单不存在');

        //是否有申请权限
        $searchWhere = [
            ['ff.projectCode', '=', $request->prjCode],
            ['fw.wxappUserUuid', '=', $request->uuid],
            ['ff.formType', '=', 1],
            ['ff.isDelete', '=', 0],
            ['fw.isDelete', '=', 0],
            ['fw.flowFormUuid', '=', $data['flowFormUuid']],
        ];
        $auth = DB::table('certificate_flowForm')
            ->alias('ff')
            ->join('certificate_flow f', 'f.uuid=ff.flowUuid')
            ->join('certificate_flowFormWorker fw', 'ff.uuid=fw.flowFormUuid')
            ->where($searchWhere)
            ->find();
        if (empty($auth)) return result(FAIL, '', '您没有申请权限');
        
        
    
        //流程是否正在进行中
        $isPending = DB::table('certificate_machineRisk')->where(['isDelete' => 0, 'machineUuid' => $machineUuid])->where([['expiredTime', '>', date('Y-m-d H:i:s')],['status','<>','-1']])->value('id');
        if ($isPending) {
            return result(FAIL,'','該設備已擁有許可證或正在申請中，請勿重複申請！');
        }
        DB::startTrans();
        try {
            //设备许可证记录
            $riskData = [
                'typeUuid'      => $machine['machineRiskTypeUuid'],
                'flowFormUuid'  => $data['flowFormUuid'],
                'flowUuid'      => $flowForm['flowUuid'],
                'wxappUserUuid' => $wxappUserUuid,
                'status'        => 0,
                'uuid'          => createUuid(),
                'areaUuid'      => $data['areaUuid'],
                'expiredTime'   => $data['expiredTime'] . ' 23:59:59',
                'machineUuid'   => $machineUuid,
                'projectCode'   => $request->prjCode,
                'corpCode'      => $request->corpCode,
            ];
            DB::table('certificate_machineRisk')->insert($riskData);

            //提交表单记录
            $recordData = [
                'riskUuid'      => $riskData['uuid'],
                'flowFormUuid'  => $data['flowFormUuid'],
                'wxappUserUuid' => $wxappUserUuid,
                'uuid'          => createUuid(),
                'formData'      => $formData,
                'flowOrder'     => $flowForm['flowOrder'],
                'projectCode'   => $request->prjCode,
                'corpCode'      => $request->corpCode,
                'checkDate'     => $data['checkDate'] ?? date('Y-m-d'),
            ];
            DB::table('certificate_machineRiskRecord')->insert($recordData);

            //附表提交
            $subFormUuids = $this->getFormDataSubForm(json_decode(html_entity_decode($formData), true))['subFormUuids'] ?? [];
            $subFormUuids = json_encode($subFormUuids, JSON_UNESCAPED_UNICODE) ?: [];
            $updateData = [
                'subFormUuids' => $subFormUuids
            ];
            //判断是否已经全部流程完成了
            $isFinish = $this->isFinish($riskData['uuid']);
            if ($isFinish) {
                $updateData['status'] = 1;
                $updateData['auditTime'] = date('Y-m-d H:i:s');
            } else {
                //记录下一个可填写的表单
                $canSubForm = $this->canSubForm($riskData['uuid']) ?: [];
                $updateData['nextFlowFormUuids'] = json_encode($canSubForm, JSON_UNESCAPED_UNICODE);
            }
            DB::table('certificate_machineRisk')->where('uuid', $riskData['uuid'])->update($updateData);
            DB::commit();
            return result(SUCCESS, ['uuid' => $riskData['uuid']], '');
        } catch (\Exception $e) {
            return result(FAIL, '', $e->getMessage());
            DB::rollback();
        }
        return result(FAIL, '', '提交失败,请重试');
    }

    /**
     * @Description: 表单审核
     * @param {Request} $request
     */
    public function audit(Request $request)
    {
        $data  = $request->data;
        $wxappUserUuid = $request->uuid;

        $riskUuid = $data['uuid'];
        $formData = is_array($data['formData']) ? json_encode($data['formData'], JSON_UNESCAPED_UNICODE) : $data['formData'];
        $formData = html_entity_decode($formData);
        $machineRisk = DB::table('certificate_machineRisk')->where(['isDelete' => 0, 'uuid' => $riskUuid])->find();
        if (!$machineRisk)  return result(FAIL, '', '许可证申请记录不存在！');
        if ($machineRisk['status'] == 1) return result(FAIL, '', '该许可证已审核通过');

        //是否有审核权限
        $searchWhere = [
            ['ff.projectCode', '=', $request->prjCode],
            ['fw.wxappUserUuid', '=', $request->uuid],
            ['ff.formType', '=', 2],
            ['ff.isDelete', '=', 0],
            ['fw.isDelete', '=', 0],
            ['fw.flowFormUuid', '=', $data['flowFormUuid']],
        ];
        $auth = DB::table('certificate_flowForm')
            ->alias('ff')
            ->join('certificate_flow f', 'f.uuid=ff.flowUuid')
            ->join('certificate_flowFormWorker fw', 'ff.uuid=fw.flowFormUuid')
            ->where($searchWhere)
            ->find();
        if (empty($auth)) return result(FAIL, '', '您没有审核权限');

        DB::startTrans();
        try {
            $flowForm = Db::table('certificate_flowForm')->where('uuid', $data['flowFormUuid'])->find();
            if (!$flowForm) return result(FAIL, '', '流程表单不存在');

            //提交表单记录
            $recordData = [
                'riskUuid'      => $riskUuid,
                'flowFormUuid'  => $data['flowFormUuid'],
                'wxappUserUuid' => $wxappUserUuid,
                'uuid'          => createUuid(),
                'formData'      => $formData,
                'flowOrder'     => $flowForm['flowOrder'],
                'projectCode'   => $request->prjCode,
                'corpCode'      => $request->corpCode,
                'checkDate'     => $data['checkDate'] ?? date('Y-m-d'),
            ];
            DB::table('certificate_machineRiskRecord')->insert($recordData);

            //附表提交
            $subFormUuids = $this->getFormDataSubForm(json_decode(html_entity_decode($formData), true))['subFormUuids'] ?? [];
            if (!empty($machineRisk['subFormUuids'])) {
                $subFormUuids = array_merge($subFormUuids, json_decode($machineRisk['subFormUuids'], true));
            }
            $subFormUuids = json_encode($subFormUuids, JSON_UNESCAPED_UNICODE) ?: [];
            $updateData = [
                'subFormUuids'      => $subFormUuids
            ];

            //判断是否已经全部流程完成了
            $isFinish = $this->isFinish($riskUuid);
            if ($isFinish) {
                $updateData['status'] = 1;
                $updateData['auditTime'] = date('Y-m-d H:i:s');
            } else {
                //记录下一个可填写的表单
                $canSubForm = $this->canSubForm($riskUuid) ?: [];
                $updateData['nextFlowFormUuids'] = json_encode($canSubForm, JSON_UNESCAPED_UNICODE);
            }
            DB::table('certificate_machineRisk')->where('uuid', $riskUuid)->update($updateData);
            DB::commit();
            return result(SUCCESS, ['uuid' => $recordData['uuid']], '提交成功');
        } catch (\Exception $e) {
            DB::rollback();
        }
        return result(FAIL, '', '提交失败,请重试');
    }

    //本流程下待填写表单
    public function canSubForm($riskUuid, $isNext = 1, $flowUuid = '', $lastFlowFormUuid = '', $lastFlowOrder = 1, $lastType = 1)
    {
        // 是否直接获取下一个表单
        if ($isNext) {
            // 获取最近一个已填写的表单记录
            $record = DB::table('certificate_machineRiskRecord')
                ->alias('rr')
                ->join('certificate_machineRisk r', 'r.uuid = rr.riskUuid')
                ->join('certificate_flowForm ff', 'ff.uuid = rr.flowFormUuid')
                ->where('rr.riskUuid', '=', $riskUuid)
                ->field('rr.flowOrder, rr.uuid, r.flowUuid, r.expiredTime, ff.type, rr.flowFormUuid')
                ->order('rr.flowOrder desc, rr.id desc')
                ->find();

            if (!$record) {
                return result(FAIL, '', '没有许可证提交记录');
            }
            $flowUuid         = $record['flowUuid'];
            $lastFlowFormUuid = $record['flowFormUuid'];
            $lastFlowOrder    = $record['flowOrder'];
            $lastType         = $record['type'];
        }

        $nextFlowOrder = $lastFlowOrder + 1;
        $canSubFormUUids = [];
        // 获取流表单数据
        $flowForms = DB::table('certificate_flowForm')
            ->where('flowUuid', '=', $flowUuid)
            ->where('isDelete', '=', 0)
            ->whereIn('flowOrder', [$lastFlowOrder, $nextFlowOrder])
            ->where('uuid', '<>', $lastFlowFormUuid)
            ->field(['uuid', 'flowOrder', 'signType'])
            ->select()
            ->toArray();

        // 处理流表单
        if (!empty($flowForms)) {
            $formUuids = array_column($flowForms, 'uuid');
            $signTypes = array_column($flowForms, 'signType');
            // 有多个表单并且存在 signType 1
            if (count($flowForms) > 1 && in_array(1, $signTypes)) {
                // 剔除当前的 lastFlowFormUuid
                $canSubFormUUids = array_filter($formUuids, function ($uuid) use ($lastFlowFormUuid) {
                    return $uuid !== $lastFlowFormUuid;
                });
            } else {
                $canSubFormUUids = $formUuids; // 直接取所有的 UUID
            }
            // 如果没有 signType 为 1
            if (!in_array(1, $signTypes)) {
                $nextFlowUuids = array_column(
                    array_filter($flowForms, function ($form) use ($nextFlowOrder) {
                        return $form['flowOrder'] == $nextFlowOrder;
                    }),
                    'uuid'
                );
                $canSubFormUUids = array_unique(array_merge($canSubFormUUids, $nextFlowUuids));
            }
        }
        // 如果类型是周表
        if ($lastType == 1) {
            // 判断是否已经完成了7天的数据
            $count = DB::table('certificate_machineRiskRecord')->where('flowFormUuid', '=', $record['uuid'])->count();
            if ($count != 7 && strtotime($record['expiredTime']) > strtotime(date('Y-m-d 23:59:59'))) {
                $canSubFormUUids[] = $record['uuid'];
            }
        }
        return array_unique($canSubFormUUids);
    }
    /**
     * @Description: 获取字典
     * @param {Request} $request
     */
    public function getOptions(Request $request)
    {
        $where = array_merge(['isDelete' => 0], $request->authWhere);

        $data['typeList'] = DB::table('certificate_machineRiskType')
            ->where($where)
            ->field(['uuid', 'name', 'subtitle'])
            ->select();
        $data['areaList'] = DB::table('certificate_area')
            ->where($where)
            ->field(['uuid', 'name'])
            ->select();
        $searchWhere = [
            ['m.projectCode', '=', $request->prjCode],
            ['md.wxappUserUuid', '=', $request->uuid],
            ['md.isDelete', '=', 0],
            ['m.isDelete', '=', 0],
            ['m.status', '=', 1],
        ];
        $data['machineList'] = DB::table('certificate_digitalMachineDriver')
            ->alias('md')
            ->join('certificate_digitalMachine m', 'm.uuid=md.digitalMachineUuid')
            ->field(['m.name', 'm.uuid', 'm.subtitle'])
            ->where($searchWhere)
            ->select();
        return result(SUCCESS, $data);
    }

    /**
     * 获取设备详情
     *
     * @param Request $request
     * @return void
     */
    public function getMachineDetail(Request $request)
    {
        $data = $request->data;

        $machineUuid = $data['uuid'];
        $machine = DB::table('certificate_digitalMachine')
            ->alias('m')
            ->join('certificate_digitalMachineType t', 't.uuid = m.digitalMacineTypeUuid')
            ->where(['m.isDelete' => 0, 'm.uuid' => $machineUuid])->field('t.machineRiskTypeUuid')
            ->find();
        if (!$machine) return result(FAIL, '', '设备不存在');

        $uuid = $machine['machineRiskTypeUuid'];
        $searchWhere = [
            ['rt.projectCode', '=', $request->prjCode],
            ['fw.wxappUserUuid', '=', $request->uuid],
            ['rt.isDelete', '=', 0],
            ['fw.isDelete', '=', 0],
            ['rt.uuid', '=', $uuid],
        ];
        $auth = DB::table('certificate_machineRiskType')
            ->alias('rt')
            ->join('certificate_flow f', 'f.uuid=rt.flowUuid')
            ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
            ->join('certificate_flowFormWorker fw', 'ff.uuid=fw.flowFormUuid')
            ->where($searchWhere)
            ->find();
        // if (empty($auth)) return result(FAIL, '', '您没有权限查看');

        $where = [
            'rt.isDelete' => 0,
            'rt.uuid' => $uuid,
            'ff.formType' => 1,
            'ff.isDelete' => 0
        ];
        $typeData = DB::table('certificate_machineRiskType')
            ->alias('rt')
            ->join('certificate_flow f', 'f.uuid=rt.flowUuid')
            ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
            ->where($where)
            ->field(['rt.uuid', 'ff.formData', 'rt.name', 'rt.uuid', 'ff.uuid as formUuid', 'ff.name as formName', 'ff.type'])
            ->find();
        if (empty($typeData)) return result(FAIL, '', '該證書已被刪除，請聯係管理員');
        $typeData['formData'] = json_decode(html_entity_decode($typeData['formData'] ?? ''), true) ?: [];
        $typeData['formData'] = $this->formatFormData($typeData['uuid'], $typeData['formData']);
        //是否有下一步操作
        $typeData['hasNext'] = $this->hasNextByMachineUuid($typeData['uuid'], $request->uuid);
        return result(SUCCESS, $typeData, '');
    }

    //许可证流程是否已经完成
    public function isFinish($riskUuid)
    {
        $isFinish = 0;
        //获取最近一个已填写的表单记录
        $record = DB::table('certificate_machineRiskRecord')
            ->alias('rr')
            ->join('certificate_machineRisk r', 'r.uuid = rr.riskUuid')
            ->join('certificate_flowForm ff', 'ff.uuid = rr.flowFormUuid')
            ->where([
                ['rr.riskUuid', '=', $riskUuid]
            ])
            ->order('rr.flowOrder desc,rr.id desc')  // 按照流程顺序降序排列
            ->find();

        if (!$record) {
            return result(FAIL, '', '没有许可证提交记录');
        }
        $nextFlowOrder = $record['flowOrder'] + 1;
        $canSubFormUUids = [];
        $flowForm = DB::table('certificate_flowForm')
            ->where([
                ['flowUuid', '=', $record['flowUuid']],
                ['isDelete', '=', 0],
                ['flowOrder', '=', $record['flowOrder']],
            ])->select()->toArray();
        $recordCount = DB::table('certificate_machineRiskRecord')
            ->alias('rr')
            ->join('certificate_machineRisk r', 'r.uuid = rr.riskUuid')
            ->where([
                ['r.flowUuid', '=', $record['flowUuid']],
                ['rr.isDelete', '=', 0],
                ['rr.flowOrder', '=', $record['flowOrder']],
            ])->count();
        if (count($flowForm) > 1 && in_array(1, array_column($flowForm, 'signType')) && $recordCount != count($flowForm)) {
            $canSubFormUUids = DB::table('certificate_flowForm')
                ->where([
                    ['flowUuid', '=', $record['flowUuid']],
                    ['isDelete', '=', 0],
                    ['flowOrder', '=', $record['flowOrder']],
                    ['uuid', '<>', $record['flowFormUuid']]
                ])->column('uuid');
        } else {
            $canSubFormUUids = DB::table('certificate_flowForm')
                ->where([
                    ['flowUuid', '=', $record['flowUuid']],
                    ['isDelete', '=', 0],
                    ['flowOrder', '=', $nextFlowOrder],
                ])->column('uuid');
        }
        if (!$canSubFormUUids) $isFinish = 1;
        return $isFinish;
    }

    public function formatFormData($typeUuid, $formData)
    {
        $domain = request()->domain();
        foreach ($formData as &$item) {
            if (isset($item['tag'])&&$item['tag'] == 'subForm') {
                $item['url'] = $domain . "/api/certificate/user/v1/MachineRiskSubForm/getSubFormTypeListByRiskType?typeUuid={$typeUuid}";
            }
        }
        return $formData;
    }

    public function getFormDataSubForm($formData)
    {
        $subFormUuids = [];
        foreach ($formData as &$item) {
            if (isset($item['tag'])&&$item['tag']== 'subForm') {
                $defaultValue = $item['defaultValue'] ?? [];
                $subFormUuids = $defaultValue ? array_merge($subFormUuids, $defaultValue) : [];
            }
        }
        return compact('subFormUuids');
    }

    /**
     * 获取表单提交详情
     *
     * @param Request $request
     * @return void
     */
    public function getRecordDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];
        $where = [
            'r.isDelete' => 0,
            'r.uuid' => $uuid
        ];
        //查看提交过的记录
        $returnData = DB::table('certificate_machineRiskRecord')
            ->alias('r')
            ->join('certificate_flowForm f', 'f.uuid = r.flowFormUuid')
            ->where($where)
            ->field('f.uuid,f.name,f.subtitle,r.formData,f.linkForms,r.riskUuid')
            ->find();
        if (!$returnData)   return result(FAIL, '', '没有提交记录');
        $returnData['formData'] = json_decode(html_entity_decode($returnData['formData']), true);
        $linkForms = $returnData['linkForms'] ? json_decode($returnData['linkForms'], true) : [];
        
        if ($linkForms) {
            $linkForms = DB::table('certificate_flowForm')
                ->alias('ff')
                ->join('certificate_machineRiskRecord r', 'r.flowFormUuid = ff.uuid')
                ->where('r.riskUuid',$returnData['riskUuid'])
                ->whereIn('ff.uuid', $linkForms)
                ->order('ff.showOrder asc,ff.flowOrder asc,r.id asc')
                ->field('r.uuid,ff.name,r.formData')
                ->group('r.uuid')
                ->select()->toArray();
            foreach ($linkForms as $key => $item) {
                $linkForms[$key]['formData'] = json_decode(html_entity_decode($item['formData']), true);
            }
        }
        $returnData['linkForms'] = $linkForms;

        return result(SUCCESS, $returnData, '');
    }

    //获取当前用户待提交表单的许可证
    public function getCurrentToSubFormUuids($wxappUserUuid)
    {
        //当前已经提交的流程表单
        $flowFormUuid = DB::table('certificate_machineRiskRecord')
            ->alias('r')
            ->join('certificate_machineRisk mr', 'mr.uuid =  r.riskUuid')
            ->where('r.wxappUserUuid', $wxappUserUuid)
            ->where('mr.status', 0)
            ->where('mr.expiredTime', '>', date('Y-m-d H:i:s'))
            ->column('r.flowFormUuid') ?? [];
        //获取当前用户拥有的待审批表单
        $flowFormUuids = DB::table('certificate_flowFormWorker')
            ->alias('w')
            ->join('certificate_flowForm ff', 'w.flowFormUuid=w.flowFormUuid')
            ->where('w.wxappUserUuid', $wxappUserUuid)
            ->where('ff.formType', 2)
            ->where('w.isDelete', 0)
            ->whereNotIn('ff.uuid', $flowFormUuid)
            ->group('w.flowFormUuid')
            ->column('w.flowFormUuid') ?: [];
        $flowFormUuids = array_unique($flowFormUuids);
        $arrList = DB::table('certificate_machineRisk')
            ->alias('r')
            ->where('r.nextFlowFormUuids', '<>', '')
            ->where('r.status', 0)
            ->field(['r.uuid', 'r.nextFlowFormUuids'])
            ->group('r.id')
            ->select()
            ->toArray();
        $arrList = array_filter($arrList, function ($item) use ($flowFormUuids) {
            $nextFlowFormUuids = json_decode($item['nextFlowFormUuids'], true);
            if (array_intersect($flowFormUuids, $nextFlowFormUuids)) {
                return true;
            }
            return false;
        });
        return array_column($arrList, 'uuid') ?: [];
    }

    public function getToSubCount($getCurrentToSubFormUuids, $data)
    {
        //待填写数量
        $searchWhere = [];
        array_push($searchWhere, ['r.uuid', 'IN', $getCurrentToSubFormUuids]);
        array_push($searchWhere, ['r.status', '=', 0]);
        array_push($searchWhere, ['r.expiredTime', '>', date('Y-m-d H:i:s')]);
        array_push($searchWhere, ['w.isDelete', '=', 0]);
        if (!empty($data['machineUuid'])) array_push($searchWhere, ['r.machineUuid', '=', $data['machineUuid']]);
        if (!empty($data['areaUuid'])) array_push($searchWhere, ['r.areaUuid', '=', $data['areaUuid']]);
        if (!empty($data['typeUuid'])) array_push($searchWhere, ['r.typeUuid', '=', $data['typeUuid']]);
        $toSubCount =  DB::table('certificate_machineRisk')
            ->alias('r')
            ->leftjoin('certificate_machineRiskType rt', 'r.typeUuid = rt.uuid')
            ->join('certificate_flowFormWorker w', 'w.wxappUserUuid = r.wxappUserUuid')
            ->where($searchWhere)
            ->group('r.id')
            ->count();
        return $toSubCount ?: 0;
    }

    public function hasAuth($request, $data)
    {
        //是否有新增权限,具有申请表权限+驾驶舱人员
        $hasAuth =  0;
        $isDriver = 1;
        $searchWhere = [
            ['rt.projectCode', '=', $request->prjCode],
            ['fw.wxappUserUuid', '=', $request->uuid],
            ['rt.isDelete', '=', 0],
            ['fw.isDelete', '=', 0],
            ['ff.formType', '=', 1],
        ];
        
         if (!empty($data['machineUuid'])) {
            //是否有驾驶员权限
            $isDriver =  DB::table('certificate_digitalmachinedriver')
            ->where([
                'isDelete'=>0,
                'wxappUserUuid'=>$request->uuid,
                'digitalMachineUuid'=>$data['machineUuid'],
            ])->value('id');
           //获取设备类型，并确认设备是否离场
            $typeUuid = DB::table('certificate_digitalMachine')
            ->where([
                'projectCode'=>$request->prjCode,
                'uuid'=>$data['machineUuid'],
                'status'=>1,
            ])->value('digitalMacineTypeUuid');
            if(!$typeUuid) return 0;
            array_push($searchWhere,["mt.uuid",'=',$typeUuid]);
        }
        
        $flowAuth = DB::table('certificate_digitalMachineType')
        ->alias('mt')
        ->join('certificate_machineRiskType rt','mt.machineRiskTypeUuid = rt.uuid')
        ->join('certificate_flow f', 'f.uuid=rt.flowUuid')
        ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
        ->join('certificate_flowFormWorker fw', 'ff.uuid=fw.flowFormUuid')
        ->where($searchWhere)
        ->value('rt.id');
        
       
        return (int)($isDriver&&$flowAuth);

        
        
 
        // $auth = DB::table('certificate_machineRiskType')
        //     ->alias('rt')
        //     ->join('certificate_digitalMachineType mt', 'rt.uuid=mt.machineRiskTypeUuid')
        //     ->join('certificate_digitalMachine m', 'm.digitalMacineTypeUuid=mt.uuid')
        //     ->join('certificate_digitalMachineDriver d', 'd.digitalMachineUuid = m.uuid')
        //     ->join('certificate_flow f', 'f.uuid=rt.flowUuid')
        //     ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
        //     ->join('certificate_flowFormWorker fw', 'ff.uuid=fw.flowFormUuid')
        //     ->where($searchWhere)
        //     ->value('rt.id');
        // if (!empty($auth)) $hasAuth =  1;
        // return $hasAuth;
    }

    public function hasNextByMachineUuid($machineTypeUuid, $wxappUserUuid)
    {
        $hasNext = 0;
        $where = [
            'rt.isDelete' => 0,
            'rt.uuid' => $machineTypeUuid,
            'ff.formType' => 1,
            'ff.isDelete' => 0
        ];
        $record = DB::table('certificate_machineRiskType')
            ->alias('rt')
            ->join('certificate_flow f', 'f.uuid=rt.flowUuid')
            ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
            ->where($where)
            ->field(['rt.uuid', 'ff.flowUuid', 'ff.uuid as flowFormUuid', 'ff.type'])
            ->find();
        if ($record) {
            //本流程下可提交的表单
            $nextFlowOrder = 2;
            $canSubFormUUids = [];
            //如果类型是周表
            if ($record['type'] == 1) {
                // 获取当前日期
                $today = new DateTime();
                // 获取当前周的周日日期
                $endOfWeek = clone $today;
                $endOfWeek->modify('sunday this week');  // 获取本周的周日
                // 以 YYYY-MM-DD 格式输出日期
                $weekEndDate = $endOfWeek->format('Y-m-d');  // 格式化为 YYYY-MM-DD
                if (strtotime($weekEndDate . ' 23:59:59') > strtotime(date('Y-m-d 23:59:59'))) {
                    $canSubFormUUids[] = $record['flowFormUuid'];
                }
            }
            $canNextSubFormUUids = DB::table('certificate_flowForm')
                ->where([
                    ['flowUuid', '=', $record['flowUuid']],
                    ['isDelete', '=', 0],
                    ['flowOrder', '=', $nextFlowOrder],
                ])->column('uuid');
            $canSubFormUUids = array_merge($canSubFormUUids, $canNextSubFormUUids);
            //获取当前用户拥有的表单信息
            $nextData = DB::table('certificate_flowForm')
                ->alias('ff')
                ->join('certificate_flowFormWorker fw', 'fw.flowFormUuid = ff.uuid')
                ->where([
                    'fw.wxappUserUuid' => $wxappUserUuid,
                    'fw.isDelete' => 0
                ])
                ->whereIn('ff.uuid', $canSubFormUUids)
                ->order('ff.flowOrder asc')
                ->field('ff.uuid')
                ->find();
            if ($nextData) $hasNext = 1;
        }
        return $hasNext;
    }
}
